package com.example.springlearn.util.redis;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * redis 基本 工具类
 */
@Slf4j
@Component
public class ToolsUtil {

    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    /**
     * 设置 redis 缓存时间
     *
     * @param key  键
     * @param time 缓存时间 妙
     * @return 设置是否成功
     */
    public boolean expire(String key, long time) {
        try {
            if (time > 0) {
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            log.warn(e.toString());
            return false;
        }
    }

    /**
     * 获取键值的剩余缓存时间
     *
     * @param key 键
     * @return 剩余缓存时间
     */
    public long getExpire(String key) {
        return redisTemplate.getExpire(key);
    }

    /**
     * 判断 键 key 是否存在
     *
     * @param key 键
     * @return 是否存在
     */
    public boolean hasKey(String key) {
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            log.warn(e.toString());
            return false;
        }
    }

    /**
     * 删除 键
     *
     * @param keys 键/单个或多个
     */
    public void del(String... keys) {
        if (keys != null && keys.length != 0) {
            if (keys.length == 1) {
                redisTemplate.delete(keys[0]);
            } else {
                redisTemplate.delete(Arrays.asList(keys));
            }
        }
    }

    /**
     * 模糊查询获取key值
     *
     * @param pattern 表达式
     */
    public Set<String> keys(String pattern) {
        return redisTemplate.keys(pattern);
    }

}
